package com.ikas.ai.server.module.flow.listener;

import com.ikas.ai.framework.core.event.FlowEvent;
import com.ikas.ai.framework.core.listener.FlowListener;
import com.ikas.ai.framework.flow.FlowStatus;
import com.ikas.ai.framework.flow.ScoreFlow;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.flow.model.FlowLog;
import com.ikas.ai.server.module.flow.service.FlowLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: 记录流程日志
 * @Author: qi.yilai
 * @Date: 2023/2/1 16:39
 * @Version: 1.0.0
 **/
@Component
public class MaintainFlowLogListener implements FlowListener {
    private static final String STARTING_LOG = "【流程】已启动";
    private static final String SUCCESS_LOG = "【流程】执行成功";
    private static final String FAILURE_LOG = "【流程】执行失败";
    private static final String STOP_LOG = "【流程】停止执行";

    @Autowired
    private FlowLogService flowLogService;

    @Override
    public boolean fireEvent(FlowEvent event) {
        ScoreFlow scoreFlow = event.getOwner();
        FlowLog flowLog = new FlowLog();
        flowLog.setSceneId(scoreFlow.getSceneId());
        flowLog.setFlowId(scoreFlow.getFlowId());
        flowLog.setFlowInstanceId(scoreFlow.getFlowInstanceId());
        flowLog.setLogType((byte)0); // 0=流程

        FlowStatus status = scoreFlow.getStatus();
        flowLog.setStatus(status.getStatus().byteValue());
        if (status == FlowStatus.CREATED) {
            return true;
        }
        String log;
        switch (status) {
            case STARTING:
                log = STARTING_LOG;
                break;
            case SUCCESS:
                log = SUCCESS_LOG;
                break;
            case FAILURE:
                log = FAILURE_LOG;
                break;
            case STOP:
                log = STOP_LOG;
                break;
            default:
                throw new BusinessException("不支持其他流程状态");
        }
        flowLog.setLog(log);
        flowLog.setCreateTime(new Date());
        flowLogService.save(flowLog);
        return true;
    }
}
